package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * \* User: ywg
 * \* Date: 2018/4/13
 * \* Time: 15:02
 * \* Description:
 * \
 */
public class TenggaoGatway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(TenggaoGatway.class);
    private static final String SUCCESS = "SUCCESS";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        String result = "自动成功";
        int status = SmsMsgStatusEnum.SEND_SUCCESS.index;
        try {
            Map<String, String> param = buildParam(entity);
            String url = info.getServerAddr();
            String response = doPost(url, param);
            String[] split = entity.getMessageId().split(",");
            if (StringUtils.isBlank(response)) {
                result = "网关请求超时";
                status = SmsMsgStatusEnum.SEND_FAIL.index;
                for (String messageId : split) {
                    receiveReport(status, messageId, result);
                }
                return;
            }
            logger.info("TenggaoGatway send url : {}, params : {}, result : {}", info.getServerAddr(), param, response);
            List<Element> contents = xmlElement(response);
            if (contents != null && contents.size() == 3) {
                String returnStatus = contents.get(0).getValue();
                //序列
                if (!SUCCESS.equalsIgnoreCase(returnStatus)) {
                    status = SmsMsgStatusEnum.SEND_FAIL.index;
                    result = returnStatus;
                }
                for (String messageId : split) {
                    receiveReport(status, messageId, result);
                }
            }
        } catch (Exception e) {
            logger.error("TenggaoGatway sendMessage error ! ", e);
        }
        return;
    }

    private Map<String, String> buildParam(SendQueueEntity entity) throws UnsupportedEncodingException {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type", "send");
        paramsMap.put("username", info.getAccount());
        String encode = MD5Util.encode(info.getPassword());
        paramsMap.put("password", encode);
        Map custom = JSON.parseObject(info.getCustom(), Map.class);
        paramsMap.put("gwid", (String) custom.get("gwid"));
        paramsMap.put("mobile", entity.getPhone());
        paramsMap.put("message", URLEncoder.encode(entity.getContent(), "utf-8"));
        logger.info("TenggaoGatway phone {}", entity.getPhone());
        return paramsMap;
    }


    public List<Element> xmlElements(String xmlDoc) {
        List<Element> children = null;
        try {
            List<Element> childrens = xmlElement(xmlDoc);
            if (childrens != null && childrens.size() > 0) {
                Element element = childrens.get(0);
                children = element.getChildren();
            }
        } catch (Exception e) {
            logger.error("TenggaoGatway xmlElements  dom error ! ", e);
        }
        return children;
    }

    //http://jk.106api.cn/statusApi.aspx?type=query&username=*****&password=*****
    @Override
    public boolean queryStatus() {
        /*try {
            int status = SmsMsgStatusEnum.SEND_FAIL.code;
            StringBuilder builder = new StringBuilder();
            builder.append("http://jk.106api.cn/statusApi.aspx");
            builder.append("?type=").append("query");
            builder.append("&username=").append(info.getAccount());
            String encode = MD5Util.encode(info.getPassword());
            builder.append("&password=").append(encode);
            String response = doGet(builder.toString());
            logger.info("TenggaoGatway queryStatus url : {}, result : {}", builder.toString(), response);
            List<Element> contents = xmlElement(response);
            String result = null;
            String messageId = null;
            if (contents != null && contents.size() == 5) {
                String taskId = contents.get(1).getValue();
                result = contents.get(4).getValue();
                messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId);
                if (SEND_SUCCESS.equals(result)) {
                    status = SmsMsgStatusEnum.SEND_SUCCESS.code;
                }
            }
            if (StringUtils.isBlank(messageId)) {
                logger.warn("TenggaoGatway notifyStatus messageId is null params : {}", messageId);
            }
            receiveReport(status, messageId, result);
            return true;
        } catch (Exception e) {
            logger.error("TenggaoGatway queryStatus error ! ", e);
        }*/
        return false;
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {

        return false;
    }

    @Override
    public boolean queryReceiveMsg() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("http://jk.106api.cn/callApi.aspx");
            builder.append("?type=").append("query");
            builder.append("&username=").append(info.getAccount());

            String encode = MD5Util.encode(info.getPassword());
            builder.append("&password=").append(encode);
            builder.append("&rece=").append("xml");
            String response = doGet(builder.toString());
            List<Element> contents = xmlElements(response);
            logger.info("TenggaoGatway queryReceiveMsg：{}", response);
            SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
            smsReceiveMessage.setCreateTime(new Date());
            if (contents != null && contents.size() == 4) {
                Element phone = contents.get(0);
                Element taskId = contents.get(1);
                String task = taskId.getValue();
                Element content = contents.get(2);
                smsReceiveMessage.setPhone(phone.getValue());
                smsReceiveMessage.setContent(content.getValue());
                smsReceiveMessage.setMessageId(task);
                receiveMessage(smsReceiveMessage);
                return true;
            }
        } catch (Exception e) {
            logger.error("TenggaoGatway queryReceiveMsg error ! ", e);
        }
        return false;
    }

    @Override
    public int queryBalance() throws Exception {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr());
            builder.append("?type=overage");
            builder.append("&username=").append(info.getAccount());
            String encode = MD5Util.encode(info.getPassword());
            builder.append("&password=").append(encode);
            builder.append("&gwid=").append("1c2145e");
            String response = HttpClientUtil.doGet(builder.toString());
            List<Element> elements = xmlElement(response);
            String overage = null;
            int ret = 0;
            try {
                if (elements != null && elements.size() > 1) {
                    Element element = elements.get(2);
                    overage = element.getValue();
                }
                logger.info("{} 余额查询结果:{}", info.getName(), overage);
                ret = Integer.parseInt(overage);
            } catch (Exception e) {
            }
            return ret;

        } catch (Exception e) {
            logger.error("TenggaoGatway queryBalance error ! ", e);
        }
        return 0;
    }
}
